#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <pthread.h>

#include <unistd.h>
#include <string.h>

#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>

// ./ai  <ip> <port>
int main(int argc, char const *argv[])
{
    if(argc !=3 ) return -1;
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in server_addr = {
        .sin_family = AF_INET,
        .sin_port = htons(atoi(argv[2])),
        .sin_addr.s_addr = inet_addr(argv[1])
    };

    // TCP客户端的连接服务
    if(connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) != 0){
        perror("connect");
        return -1;
    }

    printf("连接成功!\n");
    char buf[128] = "";
    char recv_buf[64] = "";
    while(1){
        printf("> ");
        fgets(buf, 128, stdin);
        buf[strlen(buf)-1] = 0;

        // 发送数据
        send(sockfd, buf, strlen(buf), 0);

        // 接收数据
        ssize_t len = recv(sockfd,recv_buf, 64, 0);
        if(len > 0){
            printf("%s\n", recv_buf);
        }

        if(strncmp("bye", buf, 3) == 0) break;

        bzero(buf, 128);
        bzero(recv_buf, 64);
    } 

    close(sockfd);
    printf("--exit--\n");

    return 0;
}
